package com.fengxu.gamescript.ui.setting

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ListView
import android.widget.TextView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.boot.KeySetBoot
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.other.Point
import com.fengxu.gamescript.data.other.YsKeyConf
import com.fengxu.gamescript.jsengine.api.music.GenshinAutoClick
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.util.CommonUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.sdk27.coroutines.onClick

@Deprecated("该原神键位配置页已经被废弃了，请使用通用键位配置类KeyConfActivity")
class YsSettingActivity : BaseActivity() {

    // x开始距
    val xStartTv:MaterialEditText by lazy {
        findViewById(R.id.ys_setting_xStart)
    }

    // x中心距
    val xGepTv:MaterialEditText by lazy {
        findViewById(R.id.ys_setting_xGep)
    }

    // y开始距
    val yStartTv:MaterialEditText by lazy {
        findViewById(R.id.ys_setting_yStart)
    }

    // y中心距
    val yGepTv:MaterialEditText by lazy {
        findViewById(R.id.ys_setting_yGep)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ys_setting)
        initView()
    }

    /**
     * 初始化控件
     */
    private fun initView() {
        findViewById<View>(R.id.actionbar_back).onClick { finish() }
        findViewById<TextView>(R.id.actionbar_title).text = "原神键位参数设置"
        Conf.getConf().ysKeyConf.run {
            xStartTv.setText(String.format("%.1f",getxStart()))
            xGepTv.setText(String.format("%.1f",getxGep()))
            yStartTv.setText(String.format("%.1f",getyStart()))
            yGepTv.setText(String.format("%.1f",getyGep()))
        }
        // 设置计算新键位并保存配置
        findViewById<View>(R.id.ys_setting_calcKeys).onClick {
           saveKeyConfBySystemCalc()
        }
        // 开启引导设置键位
        findViewById<View>(R.id.ys_setting_keySetBoot).onClick {
            CommonUtils.toastDialog(this@YsSettingActivity,content = "您即将开启悬浮窗引导设置原神风琴键位，开启后请根据" +
                    "悬浮窗文字提示将指定索引的圆形图标移动到指定的键位上。", positiveText = "确定开始", onPositive = {
                if(KeySetBoot.hasRunning){
                    XToast.warning(this@YsSettingActivity,"已经有引导在运行了，请勿重复运行!").show()
                    return@toastDialog
                }
                KeySetBoot(this@YsSettingActivity).run {
                    keyBootNumber = 21
                    keyBootComplete = this@YsSettingActivity::saveKeyConfByBoot
                    showBoot()
                }
            })
        }
        // 设置刷新重新加载
        findViewById<SmartRefreshLayout>(R.id.ys_setting_smartLayout).run {
            setOnRefreshListener {
                initView()
                it.finishRefresh()
            }
        }
        initAllKeyPoint()
    }


    /**
     * 初始化所有键位显示
     */
    private fun initAllKeyPoint() {
        val keyList = findViewById<ListView>(R.id.ys_setting_keyList)
        val keyPoints = Conf.getConf().ysKeyConf.keyPoints
        keyList.adapter = object :BaseAdapter(){
            override fun getCount(): Int {
                return keyPoints.size
            }

            override fun getItem(position: Int): Any {
                return keyPoints[position]
            }

            override fun getItemId(position: Int): Long {
                return position.toLong()
            }

            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
                // 不使用缓存
                return TextView(this@YsSettingActivity).apply {
                    val pcKeyStr = GenshinAutoClick.keyMap[position/7][position%7]
                    val x = String.format("%.1f",keyPoints[position].x)
                    val y = String.format("%.1f",keyPoints[position].y)
                    text = "键位索引: ${position+1}, 对应电脑键位: ${pcKeyStr} , X坐标: ${x}, Y坐标: ${y}"
                    val pd = DensityUtils.dp2px(10F)
                    setPadding(0,pd,0,pd)
                    textSize = DensityUtils.sp2px(4F).toFloat()
                    layoutParams = ViewGroup.LayoutParams(-1, -2)
                }
            }

        }
    }

    /**
     * 保存系统通过侧边距和中心距自动计算的键位
     */
    private fun saveKeyConfBySystemCalc() {
        if (!xStartTv.validate() || !xGepTv.validate() || !yStartTv.validate() || !yGepTv.validate()){
            CommonUtils.toastDialog(this,content = "您设置的数据不符合规范，无法保存!")
            return
        }
        val loadingDialog = CommonUtils.loadingDialog(this@YsSettingActivity, content = "保存配置中...")
        Conf.getConf().ysKeyConf.run {
            setxStart(xStartTv.text.toString().toDouble())
            setxGep(xGepTv.text.toString().toDouble())
            setyStart(yStartTv.text.toString().toDouble())
            setyGep(yGepTv.text.toString().toDouble())
            reCalcKeyPoints()
        }
        Conf.saveConf(this)
        initAllKeyPoint()
        loadingDialog.dismiss()
        XToast.success(this@YsSettingActivity,"配置保存成功!").show()
    }

    /**
     * 保存通过引导设置的具体键位信息
     */
    private fun saveKeyConfByBoot(points:Array<Point>){
        Conf.getConf().ysKeyConf.keyPoints = points
        Conf.saveConf(this)
    }

}